const { Controller } = require("egg");
const urlencode = require('urlencode');

class Football extends Controller {
    async paihang() {
        const { ctx } = this;
        ctx.set('Access-Control-Allow-Origin', '*');

        const sql = ` select * from football ORDER BY score DESC `;

        const res = await this.app.mysql.query(sql);

        ctx.body = res
    }
    async pushScore() {
        const { ctx } = this;
        ctx.set('Access-Control-Allow-Origin', '*');

        const {
            nick_name,
            score,
            time,
            openid,
            head_img,
        } = ctx.request.body;

        // nick_name = urlencode(nick_name, 'gbk');
        console.log(nick_name);
        // return 
        // 先查有没有这个openid
        const isOpenId = await this.app.mysql.select("football", {
            where: { openid }
        });

        // console.log(isOpenId)

        if (isOpenId.length > 0) {
            const row = {
                score,
                time
            };
            const options = {
                where: {
                    openid
                }
            }
            const upRes = await this.app.mysql.update("football", row, options);
            ctx.body = upRes
            return;
        }

        const res = await this.app.mysql.insert("football", {
            nick_name,
            score,
            time,
            openid,
            head_img,
        });

        ctx.body = res
    }
    // 获取最好成绩
    async bestScore() {
        const { ctx } = this;
        ctx.set('Access-Control-Allow-Origin', '*');

        const { openid } = ctx.request.body;

        const sql = `
            SELECT
                *
            FROM
                football
            WHERE
                football.openid = ?
            ORDER BY
                football.score DESC,
                football.time ASC
            LIMIT 0, 1 `;

        const res = await this.app.mysql.query(sql, [openid]);

        ctx.body = res
    }
    // 使用兑奖
    async useDuijiang() {
        const { ctx } = this;
        ctx.set('Access-Control-Allow-Origin', '*');

        const { openid } = ctx.request.body;
        console.log(ctx.request.body)
        const row = {
            use: 1
        };

        const options = {
            where: {
                openid
            }
        }

        const upRes = await this.app.mysql.update("football", row, options);
        ctx.body = upRes;

    }
}

module.exports = Football;